package com.csx.governance.traffic.condition.support;


import com.csx.governance.traffic.condition.ExpressionExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author cuisongxu
 * @date 2023/2/25 11:57
 */
public class ExpressionExecutors {

    private static final Logger logger = LoggerFactory.getLogger(ExpressionExecutors.class);

    public static final ExpressionExecutor FIRST_EXPRESSION_EXECUTOR = getFirstExpressionExecutor();

    private static ExpressionExecutor getFirstExpressionExecutor() {
        // 通过Java原生的SPI机制获取ExpressionExecutor.class的实现类
        Iterator<ExpressionExecutor> iterator = ServiceLoader.load(ExpressionExecutor.class).iterator();
        ExpressionExecutor firstExpressionExecutor = null;
        while(iterator.hasNext()) {
            try {
                firstExpressionExecutor = iterator.next();
                break;
            } catch (Throwable e) {
                logger.warn("New ExpressionExecutor Instance Fail because: ", e);
            }
        }
        if(firstExpressionExecutor != null) {
            logger.info("Use ExpressionExecutor: {}", firstExpressionExecutor);
        }
        return firstExpressionExecutor;
    }
}
